﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;

namespace Infrastructure.WpfClient.Converts
{
    public class StringToXamlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if (value != null)
                {
                    var xaml = value.ToString();
                    System.IO.TextReader textreader = new System.IO.StringReader(xaml);
                    var reader = XmlReader.Create(textreader);
                    var flowDocument = (FlowDocument)XamlReader.Load(reader);
                    return flowDocument;
                }
                else if (targetType.Name == typeof(FlowDocument).Name)
                {
                    var flowDocument = new FlowDocument();
                    var writter = System.Windows.Markup.XamlWriter.Save(flowDocument);
                    return writter;
                }
            }
            catch (Exception)
            {                
             
            }       
            return value;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                var flowDocument = (FlowDocument)value;
                var writter = System.Windows.Markup.XamlWriter.Save(flowDocument);
                return writter;
            }
            return value;
        }
    }
}
